package com.danjinwulian.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.danjinwulian.common.utils.http.HttpUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class WxUtils {

    public static final String MSGTYPE_EVENT = "event";//消息类型--事件
    public static final String MESSAGE_SUBSCIBE = "subscribe";//消息事件类型--订阅事件
    public static final String MESSAGE_UNSUBSCIBE = "unsubscribe";//消息事件类型--取消订阅事件
    public static final String MESSAGE_TEXT = "text";//消息类型--文本消息
    public static final String MESSAGE_CLICK = "CLICK";//消息类型-点击事件
    public static final String MESSAGE_SCAN = "SCAN";//消息类型-扫码事件

    /**
     * 验证微信签名
     */
    public static boolean checkSignature(String signature, String timestamp,String nonce, String token) {
        // 1.将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[]{token, timestamp, nonce};
        Arrays.sort(arr);
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        content = null;
        // 3.将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null && tmpStr.equals(signature.toUpperCase());
    }

    private static String byteToStr(byte[] byteArray) {
        StringBuilder strDigest = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            strDigest.append(byteToHexStr(byteArray[i]));
        }
        return strDigest.toString();
    }

    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        return new String(tempArr);
    }

    public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        HashMap<String, String> map = new HashMap<String,String>();
        SAXReader reader = new SAXReader();
        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked")
        List<Element> list = (List<Element>)root.elements();

        for(Element e:list){
            map.put(e.getName(), e.getText());
        }
        ins.close();
        return map;
    }

    /**
     * 构建普通消息
     * @param toUser 接收方账号（openId）
     * @param fromUser 开发者账号
     * @param createTime 创建时间，整型
     * @param content 内容
     * @return 回复消息
     */
    public static String getXmlReturnMsg(String toUser,String fromUser,Long createTime,String content) {
        return "<xml>\n" +
                "  <ToUserName><![CDATA["+toUser+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+fromUser+"]]></FromUserName>\n" +
                "  <CreateTime>"+createTime+"</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+content+"]]></Content>\n" +
                "</xml>";
    }

    public static String getJsapiTicket(String accessToken) {
        String jsapiTicket = "";
        String rspStr = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi");
        if (StringUtils.isNotEmpty(rspStr))
        {
            JSONObject obj = JSON.parseObject(rspStr);
            jsapiTicket = obj.getString("ticket");
        }

        return jsapiTicket;
    }

    public static Map<String, String> code2session(String appid, String secret, String code) {
        Map result = new HashMap();
        String rspStr = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code");
        if (StringUtils.isNotEmpty(rspStr))
        {
            JSONObject obj = JSON.parseObject(rspStr);
            result.put("openid", obj.getString("openid"));
            result.put("unionid", obj.getString("unionid"));
            result.put("session_key", obj.getString("session_key"));
        }

        return result;
    }

    public static Map<String, String> getUserInfo(String openId, String accessToken) {
        Map result = new HashMap();
        String rspStr = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN");
        if (StringUtils.isNotEmpty(rspStr))
        {
            JSONObject obj = JSON.parseObject(rspStr);
            result.put("openid", obj.getString("openid"));
            result.put("unionid", obj.getString("unionid"));
            result.put("nickname", obj.getString("nickname"));
            result.put("headimgurl", obj.getString("headimgurl"));
            result.put("sex", obj.getString("sex"));
            result.put("country", obj.getString("country"));
            result.put("province", obj.getString("province"));
            result.put("city", obj.getString("city"));
        }

        return result;
    }

    public static Map<String, Object> createParamsData(Object value, Object color) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("value", value);

        if (color != null && StringUtils.isNotEmpty(color.toString())) {
            params.put("color", color);
        }
        return params;
    }

    public static String createNonceStr() {
        return UUID.randomUUID().toString();
    }
}
